<?php


namespace App\Http\Repositories\Api\Qiniu;

use App\Exceptions\ApiException;
use App\Http\Repositories\BaseRepository as Repository;
use zgldh\QiniuStorage\QiniuStorage;

class QiniuRepository extends Repository
{
    const IMAGES_PREFIX = 'images/';

    /**
     *
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function uploadFile($data)
    {
        $file = $data['file'];

        // 初始化
        $disk = QiniuStorage::disk('qiniu');
        // 重命名文件
        $fileName = $this->getFileNameMd5($file);
        // 上传到七牛
        $bool = $disk->put($fileName, file_get_contents($file->getRealPath()));
        // 判断是否上传成功
        if ($bool) {
            $path = $disk->downloadUrl($fileName);

            return [
                'src' => $fileName,
                'path' => $path
            ];
        }
        throw new ApiException([1212, '上传失败']);

    }

    /**
     * 获取文件名
     * @param $file
     * @return string
     */
    public function getFileNameMd5($file)
    {
        return md5($file->getClientOriginalName()).'.'.$file->getClientOriginalExtension();
    }

    public function uploadFiles($data)
    {
        $res = [];
        foreach ($data['file'] as $v) {
//            $v = $data['file'];
            // 初始化
            $disk = QiniuStorage::disk('qiniu');
            // 重命名文件
            $fileName = $this->getFileNameMd5($v);
            // 上传到七牛
            $bool = $disk->put($fileName, file_get_contents($v->getRealPath()));

            // 判断是否上传成功
            if ($bool) {
                $path = $disk->downloadUrl($fileName);
                $res[] = [
                    'src' => $fileName,
                    'path' => $path
                ];
            }
        }
        if (empty($res))
            throw new ApiException([1212, '上传失败']);
        else
            return $res;

    }

}
